package jdklearning.concurrent.threadpool;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 使用threadPool,必须指定线程命名规则,否则不如不用
 *
 * @author shenenlu 2021年05月27日 下午14:26:51
 */
public class ThreadPoolLearning {


    static void fixedThreadPool(){
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Runnable r1 = () -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        };

        executorService.submit(r1);
    }


    static void threadPoolExecutor(){
        ExecutorService executorService = new ThreadPoolExecutor(
                10
                , 200
                , 5000
                , TimeUnit.SECONDS
                , new ArrayBlockingQueue<>(10)
                , new BasicThreadFactory.Builder()
                .namingPattern("test-thread-pool-%d")
                .daemon(true)
                .priority(Thread.MAX_PRIORITY)
                .build()
            , new ThreadPoolExecutor.CallerRunsPolicy()
//            , new ThreadPoolExecutor.AbortPolicy()
//            , new ThreadPoolExecutor.DiscardOldestPolicy()
//            , new ThreadPoolExecutor.DiscardPolicy()
//                //队列满阻塞
//                , (r, executor) -> {
//                    if (!executor.isShutdown()) {
//                        try {
//                            // 主线程将会被阻塞
//                            executor.getQueue().put(r);
//                        } catch (InterruptedException e) {
//                            // should not be interrupted
//                        }
//                }
        );
        Runnable r1 = () -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        };

        executorService.submit(r1);
    }


    public static void main(String[] args) {
        fixedThreadPool();
    }
}
